#coding=utf8

from base import TBase

class Trade(TBase):
    typename = 'trade'
    fields='seller_nick,buyer_nick,title,type,created,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders'
    def sold_get(self, sessionkey, fields='', page_no=1, page_size=100):
        self.session = sessionkey
        self.method = 'trades.sold.get'
        self.setParams(page_no=page_no)
        self.setParams(page_size=page_size)
        for i in range(3):
            try:
                r = self.do()
                return r
            except Exception as e:
                error_code, msg, sub_code = e.args[0]
                if error_code == 520 and sub_code == 'isp.remote-service-timeout' and i != 2:
                    continue
                else:
                    raise

    def get(self, sessionkey, tid):
        self.session = sessionkey
        self.setParams(tid=tid)
        self.method = 'trade.get'
        return self.do()

    def _trade_do(self, sessionkey, fields=''):
        self.session = sessionkey
        if fields:
            self.fields=fields
        r = []
        n=1
        while True:
            rt = self.do(page_size=100, page_no=n)
            if not rt:
                break 
            if rt['total_results'] == 0:
                break
            r.extend(rt['trades']['trade'])
            n+=1 
            if len(r) >= rt['total_results']:
                break
        return r


if __name__ == '__main__':
    a = Trade()
    import json
    fw = open('aaaaaaaaaaaa.json', 'w')
    #json.dump(a.sold_get('610072547799b33ae3eee33d0cc47258a1edb71687776ca96124973', page_no=1, page_size=5), fw)
    #print a.sold_get('6100e17d82db4042e22c805c9106b732e62a47987623157653848668', page_no=1, page_size=5)
    print a.sold_get('6100830108c6629bc87406b2456bbc8d782cfc175620c68420839839', page_no=1, page_size=5)
    #json.dump(a.get('61019263bdcac9df240e361cd207fe59fc10ab0b651cc4639636564', 102007815047433), fw)
